import pygame
import math


def get_distance(sprite1, sprite2):
    return math.sqrt(math.fabs(sprite1.rect.centerx - sprite2.rect.centerx) ** 2
                     + math.fabs(sprite1.rect.centery - sprite2.rect.centery) ** 2)

def sprite_pixel_collidet(sp1, sp2):
    rect1 = sp1.rect;       
    rect2 = sp2.rect;                            
    rect  = rect1.clip(rect2)
    x1 = rect.x-rect1.x
    y1 = rect.y-rect1.y
    x2 = rect.x-rect2.x
    y2 = rect.y-rect2.y
    # compare the 4th element of Color, if both of the iamges's 4th elements
    # are non_zero, then we can say that these images are pixel collisioned
    for r in xrange(0, rect.height):      
        for c in xrange(0, rect.width):
                if sp1.image.get_at((c+x1, r+y1))[3] & sp2.image.get_at((c+x2, r+y2))[3]:
                    return 1        
    return 0

def get_collidet_sg(sprite, group):

    target_sprite = None

    nearest_dis = -1
    
    for s in group.sprites():
        if s.rect.colliderect(sprite.rect):     #colli with sprite
                if (sprite_pixel_collidet(s, sprite)):
                    dis = get_distance(sprite,s)
                    if (nearest_dis == -1 or nearest_dis > dis):
                            nearest_dis = dis
                            target_sprite = s

    return target_sprite

def get_collidet_sg_area(sprite, group, R):

    target_sprite = []
    
    for s in group.sprites():
        dis = get_distance(s, sprite)
        if (dis < R):
            target_sprite.append(s)

    return target_sprite
